package com.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.component.domain.*;
import com.component.domain.vo.NoteStatusVo;
import com.component.enumitem.NoteDataTypeEnum;
import com.component.enumitem.NoteStatusEnum;
import com.component.service.*;
import com.system.common.ContextUtils;
import com.system.common.Result;
import com.component.domain.vo.ContentVo;
import com.system.security.IsSecurity;
import com.system.security.SecurityUtil;
import com.system.security.domain.SelfUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/6 0:40
 * @since JDK 1.8
 */
@RestController
@Api(tags = {"内容服务层"})
@Validated
@RequestMapping("note")
public class NoteApi {

    @Autowired
    private MChannelService mChannelService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private ContentService contentService;

    @ApiModelProperty("内容搜索")
    @GetMapping("search")
    public JSONObject searchController(@RequestParam("channelId")String channelId,
                                       @RequestParam(value = "title",required = false)String title,
                                       @RequestParam(value = "tag",required = false)String tag,
                                       @RequestParam(value = "beforeDate",required = false)Date beforeDate,
                                       @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                       @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        IPage<Note> page=noteService.pageIPage(pageNum,pageSize,channelId,tag,title,beforeDate);
        return Result.successInfo(page);
    }

    @ApiOperation("设置待办")
    @PostMapping("/setstatus")
    public JSONObject setStatus(@RequestBody NoteStatusVo vo){
       boolean s=noteService.setStatus(vo);
       if(s){
           return Result.successInfo("设置成功");
       }else {
           return Result.errorInfo("设置失败");
       }
    }

    @ApiModelProperty("文章栏目移动")
    @PostMapping("/movechannel")
    public JSONObject moveChannelController(@RequestBody JSONObject json){
        if(json.get("channelId")==null){
            return Result.errorInfo("栏目不存在");
        }
        MChannel channel=mChannelService.getById(json.get("channelId").toString());
        if(channel==null){
            return Result.errorInfo("栏目id不存在");
        }
        if(json.get("data")==null){
            return Result.errorInfo("未选择数据");
        }
        Object obj=json.get("data");
        if(obj instanceof JSONArray){
           JSONArray array=(JSONArray) obj;
           List<String> strings=new ArrayList<>();
           for (int i = 0; i < array.size(); i++) {
               strings.add(array.getString(i));
           }
           this.noteService.updateNoteChannel(channel.getId().toString(),strings);
        }
        return Result.successInfo("移动成功");
    }


    @ApiModelProperty("内容分页")
    @GetMapping("page")
    public JSONObject notePageController(@Min(1) @RequestParam(value = "page",defaultValue = "1")
                                             @ApiParam("页码") Integer page,
                                         @Max(20)@RequestParam(value = "size",defaultValue = "10")
                                                 @ApiParam("条数")Integer size,
                                         @RequestParam(value = "ispri",defaultValue = "false")Boolean ispri,
                                         @RequestParam(value = "channelpath",required = false)String channelpath,
                                         @RequestParam(value = "title",required = false)String title,
                                         @RequestParam(value = "tag",required = false)String tag,
                                         @RequestParam(value = "createdate",required = false)String date,
                                         @ApiParam("关键字")@RequestParam(value = "keyword",required = false)String keyword){

        String channelId=null;
        if(channelpath!=null && !"".equals(channelpath) && (!"db_path".equals(channelpath) && !"yb_path".equals(channelpath))){
            MChannel mChannel=mChannelService.getMChannelByPath(channelpath);
            if(mChannel != null){
                channelId = mChannel.getId().toString();
            }
        }
        Map<String,Object> query=new HashMap<>();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(tag)){
            query.put("tag",tag);
        }
        if(org.apache.commons.lang3.StringUtils.isNotBlank(title)){
            query.put("title",title);
        }
        if(org.apache.commons.lang3.StringUtils.isNotBlank(date)){
            query.put("date", date);
        }
        if("db_path".equals(channelpath)){
            query.put("status", NoteStatusEnum.DB_STATUS.getStatus());
        }
        if("yb_path".equals(channelpath)){
            query.put("status",NoteStatusEnum.YB_STATUS.getStatus());
        }
        IPage<Note> page1=noteService.notePageListByKeyWord(page,size,channelId,keyword,query,ispri);
        return Result.successInfo("操作成功",page1);
    }

    @ApiModelProperty("时间搜索测试")
    @GetMapping("/test")
    public JSONObject noteDateSearchController()throws Exception{
        SimpleDateFormat dft=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date=dft.parse("2021/06/08 00:00:00");

        System.out.println(date);
        LambdaQueryWrapper<Note> noteLambdaQueryWrapper=new LambdaQueryWrapper<>();
        noteLambdaQueryWrapper.ge(Note::getCreateTime,date);

        List<Note> notes=noteService.list(noteLambdaQueryWrapper);
        return Result.successInfo("success",notes);
    }

    @Autowired
    private MNoteVersionService mNoteVersionService;

    @Autowired
    private MModelService mModelService;

    @ApiModelProperty("笔记新增")
    @PostMapping("save")
    public JSONObject saveNoteController(@RequestBody ContentVo content){
        SelfUserEntity userEntity= SecurityUtil.getSelfUserEntity();
        MChannel mChannel=mChannelService.getById(content.getChannelId());
        if(mChannel==null){
            return Result.errorInfo("栏目不存在");
        }
        Note note=new Note();
        if(org.apache.commons.lang3.StringUtils.isNotBlank(mChannel.getModelId())){
            note.setDatatype(NoteDataTypeEnum.JSON.getDataType());
        }else {
            note.setDatatype(NoteDataTypeEnum.HTML.getDataType());
        }
        note.setTitle(content.getTitle());
        note.setTag(content.getTag());
        note.setViewnum(0);
        note.setUserid(userEntity.getUserId().toString());
        //内容加密
        note.setIsEncrypt(true);
        note.setChannelId(content.getChannelId());
        note.setChangeStatus("0");
        if(mChannel.getIsprivate()){
            note.setIsprivate(mChannel.getIsprivate());
        }else {
            note.setIsprivate(false);
        }
        note.setStatus("0");
        noteService.save(note);
        Content content1=new Content();
        content1.setNid(note.getId());
        String contentStr="";
        if(org.apache.commons.lang3.StringUtils.isNotBlank(mChannel.getModelId())){
            JSONObject json=new JSONObject();
            JSONArray array=content.getArray();
            JSONArray model=content.getModel();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(mChannel.getModelId())){
                MModel mModel=mModelService.getById(mChannel.getModelId());
                if(mModel != null){
                    model=mModelService.getModelArray(mModel);
                }
            }
            Map<String,String> formula=mModelService.getAllFormulations(model);
            mModelService.getArrayByModelDataType(array,model);
            mModelService.formulationsDealData(formula,array);
            json.put("formula",formula);
            json.put("model",model==null ? new JSONObject():model);
            json.put("array",array ==null ? new JSONArray() : array);
            contentStr= ContextUtils.encrpytHex(JSONObject.toJSONString(json));
        }else {
            contentStr= ContextUtils.encrpytHex(content.getContent());
        }
        content1.setContent(contentStr);
        contentService.save(content1);
        /**
         * 保存版本
         */
        mNoteVersionService.addMNoteVersion(note.getId().toString(),note.getTitle(),content.getChannelId(),contentStr);
        return Result.successInfo("新增成功",note.getId());

    }

    /**
     * 插叙内容通过内容id
     * @return
     */
    @ApiModelProperty("内容查询")
    @GetMapping("get")
    public JSONObject contentByNidController(@RequestParam("nid")@ApiParam("内容id") Integer nid){
       Content content=contentService.getContentByNid(nid);
       if(content.getIsencrypt()){
          String contStr= ContextUtils.decryptStr(content.getContent());
          content.setContent(contStr);
       }
       noteService.addOneNoteReadCountByNid(nid);

       return Result.successInfo("success",content);
    }


    @ApiModelProperty("内容修改")
    @PostMapping("update")
    public JSONObject updateContentController(@NotNull@RequestBody ContentVo contentVo){
        if(StringUtils.isEmpty(contentVo.getId())){
            return Result.errorInfo("id不得为空");
        }
        MChannel mChannel=mChannelService.getById(contentVo.getChannelId());
        if(mChannel==null){
            return Result.errorInfo("栏目不存在");
        }
        SelfUserEntity userEntity= SecurityUtil.getSelfUserEntity();
        Note note=noteService.getById(contentVo.getId());
        note.setTitle(contentVo.getTitle());
        note.setTag(contentVo.getTag());
        note.setIsEncrypt(true);
        note.setChangeStatus("0");
        note.setChannelId(contentVo.getChannelId());
        note.setUserid(userEntity.getUserId().toString());


        noteService.updateById(note);

        LambdaQueryWrapper<Content> contentLambdaQueryWrapper=new LambdaQueryWrapper<>();
        contentLambdaQueryWrapper.eq(Content::getNid,note.getId());
        Content content=contentService.getOne(contentLambdaQueryWrapper,true);
        String contentStr="";
        if(org.apache.commons.lang3.StringUtils.isNotBlank(note.getDatatype()) &&
                note.getDatatype().equals(NoteDataTypeEnum.JSON.getDataType())){
            JSONObject json=new JSONObject();

            JSONArray array=contentVo.getArray();
            JSONArray model=contentVo.getModel();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(mChannel.getModelId())){
                MModel mModel=mModelService.getById(mChannel.getModelId());
                if(mModel != null){
                    model=mModelService.getModelArray(mModel);
                }
            }
            Map<String,String> formula=mModelService.getAllFormulations(model);
            mModelService.getArrayByModelDataType(array,model);
            mModelService.formulationsDealData(formula,array);
            json.put("formula",formula);
            json.put("model",model==null ? new JSONObject():model);
            json.put("array",array==null ? new JSONArray() : array);
            contentStr= ContextUtils.encrpytHex(JSONObject.toJSONString(json));
        }else {
            contentStr=ContextUtils.encrpytHex(contentVo.getContent());
        }
        content.setContent(contentStr);
        contentService.updateById(content);
        mNoteVersionService.addMNoteVersion(note.getId().toString(),note.getTitle(),contentVo.getChannelId(),contentStr);
        return Result.successInfo();

    }

    @ApiModelProperty("内容删除")
    @GetMapping("delete")
    public JSONObject deleteController(@RequestParam("id")Integer id){
        Note note=noteService.getById(id);
        if(note==null){
            return Result.successInfo("内容不存在");
        }
        noteService.removeById(id);
        return Result.successInfo("删除成功");
    }
}
